package Net;

import Dialog.LocalHostIPDialog;
import MainBoard.PVPMainBoard;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client extends NetContainer {
    private Socket socketOnClient;
    private String opponentIP;
    private boolean isConnecting;
    private PVPMainBoard pvpMainBoard;

    /**
     * 客户端构造函数
     *
     * @param opponentIP   服务器IP
     * @param pvpMainBoard 游戏主界面
     */
    public Client(String opponentIP, PVPMainBoard pvpMainBoard) {
        this.opponentIP = opponentIP;
        this.pvpMainBoard = pvpMainBoard;
    }

    /**
     * 更改服务器连接状态
     *
     * @param connecting 服务器的连接状态
     */
    public void setConnecting(boolean connecting) {
        isConnecting = connecting;
    }

    /**
     * 初始化IO流
     *
     * @throws IOException
     */
    @Override
    public void initIO() throws IOException {
        in = new DataInputStream(socketOnClient.getInputStream());
        out = new DataOutputStream(socketOnClient.getOutputStream());
    }

    /**
     * 客户端运行函数
     */
    @Override
    public void run() {
        try {
            socketOnClient = new Socket(opponentIP, 1921);
        } catch (Exception e) {
            e.printStackTrace();
            pvpMainBoard.getLocalHostIPDialog().getLocalHostLabel().setText("加入房间失败，请重试。");
            pvpMainBoard.getLocalHostIPDialog().setVisible(true);
            if (pvpMainBoard.getLocalHostIPDialog().getMessage() == LocalHostIPDialog.confirm) {
                pvpMainBoard.getLocalHostIPDialog().setVisible(false);
            }
            pvpMainBoard.getButtonStart().setVisible(false);
            pvpMainBoard.getButtonBack().setVisible(false);
            pvpMainBoard.getButtonCreate().setVisible(true);
            pvpMainBoard.getButtonJoin().setVisible(true);
            pvpMainBoard.getButtonCreate().setEnabled(true);
            pvpMainBoard.getButtonJoin().setEnabled(true);
        }
        try {
            initIO();
            isConnecting = true;
            System.out.println("成功连接");
            if (isConnecting) {
                pvpMainBoard.getProcessLabel().setText("等待双方准备");
                pvpMainBoard.getButtonCreate().setVisible(false);
                pvpMainBoard.getButtonJoin().setVisible(false);
                pvpMainBoard.getButtonStart().setVisible(true);
                pvpMainBoard.getButtonBack().setVisible(true);
            }
            while (isConnecting);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接已断开");
            isConnecting = false;
        }
    }
}
